﻿using AutoMapper;
using commodity.Dtos;
using commodity.Models;
using commodity.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace commodity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class CommodityController : ControllerBase
    {
        private ICommodityRepository _commodity;
        private IMapper _mapper;
        public CommodityController(ICommodityRepository commodity,IMapper mapper) 
        {
            _commodity = commodity;
            _mapper = mapper;
        }
        [HttpGet]
        [Authorize]
        public async Task<ReturnJson> FirstsCommodityMenus([FromQuery] CategoriesDto categoriesDto)
        {
            
            var menu= _mapper.Map<IEnumerable<FirstsCommdityMenuDto>>((await _commodity.GetAllData(categoriesDto.Type)));
           
            if (categoriesDto.Pagenum == null || categoriesDto.Pagesize == null)
            {
                return new ReturnJson
                {
                    Data = new { data = _mapper.Map<IEnumerable<CatDto>>(menu),Count = menu.Count() },
                    Message = "获取成功",
                    Status = 200
                };
            }
            else 
            {
                int pageNum =(int)categoriesDto.Pagenum;
                int pageSize=(int)categoriesDto.Pagesize;
                return new ReturnJson
                {
                    Data = new { data= _mapper.Map<IEnumerable<CatDto>>(menu.Skip((pageNum-1)*pageSize).Take(pageSize)), Count = menu.Count() },
                    Message = "获取成功",
                    Status = 200
                };
            }

        }
        [HttpOptions]
        public IActionResult Options() 
        {
            return Ok();
        }
        [HttpPost]
        public async Task<ReturnJson> AddCate([FromBody] AddCateFromDto addCateFromDto) 
        {
            
           await _commodity.addCateFromByCateFromAsync(addCateFromDto);
            if (!(await _commodity.SaveAsync())) 
            {
                return new ReturnJson
                {
                    Data = null,
                    Status = 404,
                    Message = "保存失败",
                };
            };
            return new ReturnJson
                {
                Data = null,
                    Status = 200,
                    Message = "保存成功",
                };

        }
    }
}
